using System;
using Tools.Domain.Common.StateMachine;
using Webshop20.Domain.Orders.Processes.Events;
using Webshop20.Domain.Orders.Core;
using Webshop20.Domain.Orders.Processes.States;

namespace Webshop20.Domain.Orders.Processes.Actions
{
    public class PassedToCarrierAction : IStateAction
    {
        public IState Execute(IStateEvent currentEvent, IStateContext context)
        {
            var orderProcess = context as OrderProcess;
            var passedToCarrierEvent = currentEvent as PassedToCarrierEvent;
            IState newState = new ShippedState();

            var billingTerm = orderProcess
                .OrderInProgress
                .Payment
                .GetBillingTerm(orderProcess.OrderInProgress.Date);

            if (billingTerm.Equals(orderProcess.OrderInProgress.Date) && orderProcess.OrderInProgress.IsPayed)
                newState = new FinishedState();
            else
            {
                passedToCarrierEvent
                    .CalendarService
                    .SetNewPointOfTimeForProcessContinuation(orderProcess.Id, billingTerm, typeof(EndOfTermsEvent));
            }

            var nameValues = passedToCarrierEvent.NotificationMailTranslator.ConvertOrderDataToNameValues(orderProcess.OrderInProgress);
            var template = passedToCarrierEvent.TemplateService.GetTemplate("ORDER_DELIVERED", nameValues);
            passedToCarrierEvent.MailService.SendMail(orderProcess.OrderInProgress.PurchaserEMail, "Bestaetigung", template);

            return newState;
        }
    }
}